package com.lzp.service.impl;

import com.lzp.mapper.StuMapper;
import com.lzp.pojo.Stu;
import com.lzp.service.StuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author lzp
 * @date 2020/6/27
 */
@Service
public class StuServiceImpl implements StuService {
    @Autowired
    public StuMapper stuMapper;

    // 查询事务可有可无，根据需求添加
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Stu getStuInfo(int id) {
        return stuMapper.selectByPrimaryKey(id);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void saveStu() {
        Stu stu = new Stu();
        stu.setName("lzp");
        stu.setScore(12);
        stuMapper.insert(stu);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void updateStu(int id) {
        Stu stu = new Stu();
        stu.setId(id);
        stu.setName("lucy");
        stu.setScore(20);
        stuMapper.updateByPrimaryKey(stu);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void deleteStu(int id) {
        stuMapper.deleteByPrimaryKey(id);
    }

    /* 测试事务传播 */
    // @Transactional(propagation = Propagation.NESTED)
    @Override
    public void saveParent() {
        Stu stu = new Stu();
        stu.setName("parent");
        stu.setScore(100);
        stuMapper.insert(stu);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void saveChildren() {
        saveChild1();
        int a = 1 / 0;
        saveChild2();
    }

    @Transactional(rollbackFor = IllegalArgumentException.class)
    @Override
    public void saveStuWithRollbackFor() {
        Stu stu = saveChild();
        if ("child".equals(stu.getName())) {
            throw new IllegalArgumentException("非法参数异常，事务回滚！");
        }
    }

    @Transactional(noRollbackFor = {IllegalArgumentException.class, ArithmeticException.class})
    @Override
    public void saveStuWithoutRollbackFor() {
        saveChild();
        int a = 1 / 0; // 算术异常，此时不回滚
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void saveChild1() {
        Stu stu = new Stu();
        stu.setName("child-1");
        stu.setScore(60);
        stuMapper.insert(stu);
    }

    private void saveChild2() {
        Stu stu = new Stu();
        stu.setName("child-2");
        stu.setScore(40);
        stuMapper.insert(stu);
    }

    private Stu saveChild() {
        Stu stu = new Stu();
        stu.setName("child");
        stu.setScore(40);
        stuMapper.insert(stu);
        return stu;
    }
}
